package com.sxt.feign.core.aspect;

import com.sxt.feign.core.enums.HystrixStatus;
import com.sxt.feign.core.fun.HystixCmd;
import com.sxt.feign.core.fun.funImpl.HystixCmdImpl;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 熔断器切面
 * @author LSX
 * @create 2019/8/22
 */

@Aspect
@Component
public class HystrixAspect {

    /**
     * 初始化一个map容器，用于存放每个请求的熔断器
     */
    private Map<String, HystixCmd> hystrixMap =  new HashMap<String,HystixCmd>();
    {
        hystrixMap.put("server-id",new HystixCmdImpl());
    }

    @Around("@annotation(com.sxt.feign.core.anno.HystixCmdRpc)")
    public Object interceptor(ProceedingJoinPoint point){
        //根据读服务的得到服务的熔断器
        HystixCmd hystixCmd = hystrixMap.get("server-id");
        // 得到服务自己熔断器的状态
        HystrixStatus status = hystixCmd.getStatus();
        switch (status){
            // 熔断器打开，拦截请求
            case OPEN:
                return hystixCmd.interceptor(point);
            // 熔断器关闭，通过请求
            case CLOSE:
                return hystixCmd.pass(point);
            // 熔断器半开，少许检查并测试请求
            case HALF_OPEN:
                return  hystixCmd.check(point);
            default:
                break;
        }
        // 不符合以上条件的返回空
        return null;
    }
}
